<?php
/**
 * Created by PhpStorm.
 * User: andy
 * Date: 2020/1/13
 * Time: 下午2:22
 */

namespace app\sms\controller;

use AlibabaCloud\Client\AlibabaCloud;
use AlibabaCloud\Client\Exception\ClientException;
use AlibabaCloud\Client\Exception\ServerException;

class SendSms
{
    /**
     * 发送短信
     * @param $mobile 手机号码
     * @param $code 验证码
     * @param int $type 类型：0 注册，1 找回密码，2 验证码登陆
     * @return int 返回：0 失败，1 成功
     * @throws ClientException
     */
    public static function send($mobile,$code,$type=0) {
        //产品名称:云通信短信服务API产品
        $product = "Dysmsapi";

        //产品Key
        $accessKeyId="LTAI4FdnYBC5P19BR7EL6qAe";

        //AccessKeySecret
        $AccessKeySecret="UwLf5swazmOavrHQ1Mrg9XtHiIORz1";

        // 暂时不支持多Region
        $region = "cn-chongqing";

        //产品域名,开发者无需替换
        $domain = "dysmsapi.aliyuncs.com";


        AlibabaCloud::accessKeyClient($accessKeyId,$AccessKeySecret)
            ->regionId($region)
            ->asDefaultClient();

        $temp="SMS_182490099";
        if($type==1){
            $temp="SMS_182490098";
        }else if($type==2){
            $temp="SMS_182490101";
        }else if($type==3){
            $temp="SMS_182490097";
        }

        try {
            $result = AlibabaCloud::rpc()
                ->product($product)
                ->version('2017-05-25')
                ->action('SendSms')
                ->method('POST')
                ->host($domain)
                ->options([
                    'query' => [
                        'RegionId' => $region,
                        'PhoneNumbers' => $mobile,
                        'SignName' => "小白二手车",
                        'TemplateCode' => $temp,
                        'TemplateParam' => "{'code':'{$code}'}",
                    ],
                ])
                ->request();
            $data=$result->toArray();

            if($data["Code"]=="OK"){
                return 1;
            }else{
                return 0;
            }

        } catch (ClientException $e) {
            //return $e->getErrorMessage() . PHP_EOL;
            return 0;
        } catch (ServerException $e) {
            //return $e->getErrorMessage() . PHP_EOL;
            return 0;
        }
    }

}